<?php
class GridTreeControl extends GridControl
{
    protected $closedLevels;
    protected $openLevels;
    protected $cssClass = 'tree hashable';
    protected $jsFile = 'GridTreeControl';
    protected $jsClass = 'GridTreeControl';
    protected $templateFile = 'Grid';

    protected function LoadView()
	{
		$this->view = new GridTree($this->viewName);
	}

    protected function RepeatRow()
	{
    	$this->RepeatTree('row', $this->view->data, $this->view->GetViewModel()->childKey, array($this, 'FormatRow'));
	}

    protected function GetState($id, $node, $level)
	{
		if ($this->view->GetViewModel()->expandAll)
            $this->view->openNodes[] = $id;
		$state = ModelTree::IsNodeOpen($node) ? 'node_collapse' : 'node_expand';
		$state .= ModelTree::IsNodeLeaf($node) ? ' node_leaf' : null;
		$state .= ModelTree::IsNodeLast($node) ? ' node_last' : null;
		return $state;
	}

    protected function GetNode($id, $label, $node, $level)
	{
		$this->closedLevels[$level] = false;

		$state = $this->GetState($id, $node, $level);
		$nodeview = "<div class='node_button $state'><div class='node_icon'>$label</div></div>";
		$nodeview = $this->IndentNode($nodeview, $level);

        if (ModelTree::IsNodeLast($node))
            $this->closedLevels[$level] = true;

		return $nodeview;
	}

    protected function IndentNode($nodeview, $level)
	{
		for ($i=0; $i<$level; $i++)
		{
			$indent = $level - $i - 1;
			$class = $this->closedLevels[$indent] ? 'blank_indent' : null;
			$nodeview = "<div class='node_indent $class'>$nodeview</div>";
		}
		return $nodeview;
	}

    protected function GetFormatedCell($value, $field, $node, $level)
	{
        $value = parent::GetFormatedCell($value, $field, $node);
        $id = $this->GetKey($node);
		switch ($field->formatType)
		{
			case VmConfig::GetInstance()->FIELDTYPE_TREE:
				$value = $this->GetNode($id, $value, $node, $level);
				break;
			case VmConfig::GetInstance()->FIELDTYPE_TREE_SELECT:
				$value = isset($field->selectList[$value]) ? $field->selectList[$value] : null;
				$value = $this->GetNode($id, $value, $node, $level);
				break;
		}
		return $value;
	}

    protected function GetNodeStates()
	{
		$gridname = $this->name;
		$open_nodes = implode($this->view->separator, $this->view->openNodes);
		$closed_nodes = implode($this->view->separator, $this->view->closedNodes);

		return "<input class='open_nodes' name='open' type='hidden' value='$open_nodes' />
		<input class='closed_nodes' name='closed' type='hidden' value='$closed_nodes' />";
	}
}
?>